public class Solution31 {
    public void nextPermutation(int[] nums) {
        int i = nums.length - 1;
        while (i > 0) {
            if (nums[i] > nums[i - 1]) {
                break;
            }
            i--;
        }
        if (i > 0) {
            for (int j = nums.length - 1; j >= i; j--) {
                if (nums[j] > nums[i - 1]) {
                    swap(nums, i - 1, j);
//                List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());
//                Collections.reverse(list.subList(i, list.size()));
//                nums = list.stream().mapToInt(Integer::intValue).toArray();
                    break;
                }
            }
        }
//        List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());
//        Collections.reverse(list);
//        return list.stream().mapToInt(Integer::intValue).toArray();
        reverse(nums, i);
    }

    private void swap(int[] nums, int a, int b) {
        nums[a] ^= nums[b];
        nums[b] ^= nums[a];
        nums[a] ^= nums[b];
    }

    private void reverse(int[] nums, int start) {
        int n = nums.length - 1;
        int i = 0;
        while (start + i < n - i) {
            swap(nums, start + i, n - i);
            i++;
        }
    }
}
